﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using NougakudoCompanion.Commons;

namespace AdminWeb.Models
{
    public class NougakudoLogs
    {
        Runtime runtime;

        List<string> instances;
        Dictionary<string, string[]> logs;          // Key=InstanceID, Value=Applications list.

        public NougakudoLogs(Runtime runtime)
        {
            this.runtime = runtime;
            instances = Helper.GetInstanceIDs(runtime);
            GetLogData();
        }

        public List<string> Instances { get { return instances; } }
        public Dictionary<string, string[]> Logs { get { return logs; } }

        void GetLogData()
        {
            logs = new Dictionary<string, string[]>();
            foreach (var instance in instances)
            {
                string file = "";
                if (instance == runtime.Environment.RoleInstanceID)
                {
                    file = Path.Combine(runtime.Environment.RuntimeFolder, Constants.RUNNING_NOUGAKUDO);
                }
                else
                {
                    file = Helper.GetDataFromBlob(runtime, Constants.RUNNING_NOUGAKUDO, instance);
                }
                logs[instance] = GetData(instance, file);
            }
        }

        string[] GetData(string instance, string file)
        {
            string[] rows = new string[]{};
            try
            {
                if (File.Exists(file))
                    rows = File.ReadAllLines(file);
            }
            catch
            {
                //return new string[] { };

            }
            // Translate from array to Apps dictionary.
            var details = new Dictionary<string, string>();
            foreach (var row in rows)
            {
                var cols = Helper.GetColums(row);
                details[cols[0]] = row;
            }

            // Add running status
            var datas = new List<string>();
            if (runtime.Applications != null)
            {
                foreach (var app in runtime.Applications.Keys)
                {
                    var find = details.ContainsKey(app);
                    if (find)
                    {
                        datas.Add("running\t" + details[app]);
                    }
                    else
                    {
                        datas.Add("stop\t" + app + "\t\t\t\t");
                    }
                }
            }

            return datas.ToArray();
        }

    }
}